//
//  HNSettingViewController.m
//  JHFBaseProject
//
//  Created by 朱传正 on 2016/12/16.
//  Copyright © 2016年 好牛. All rights reserved.
//

#import "HNSettingViewController.h"
#import "LoginViewController.h"
#import "AddressListController.h"
#import "HNChangeNicknameController.h"
#import "HNChangePwdController.h"

@interface HNSettingViewController ()<UINavigationControllerDelegate,UIActionSheetDelegate,UIImagePickerControllerDelegate>

@property (nonatomic,assign)CGFloat contentHeight;

@property (nonatomic,retain) UIImagePickerController * imagePicker;


@property (nonatomic,strong) UIImageView *imageView;
@property (nonatomic,strong) NSString *imageStr;

@property (nonatomic,strong) UILabel *username;

@property (nonatomic,strong) NSDictionary *userInfo;

@end

@implementation HNSettingViewController

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    if([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    }

}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    //在其他离开改页面的方法同样加上下面代码
    if([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    }
}


-(void)viewWillAppear:(BOOL)animated{
    [self setUserInfo];
}

-(void)setUserInfo{
    NSDictionary *userInfo = [AppConfig getUserInfo];
    
    NSString *imageStr = [NSString stringWithFormat:@"%@%@",url_Base,[userInfo objectForKey:@"photo"]];
    [_imageView sd_setImageWithURL:[NSURL URLWithString:imageStr] placeholderImage:[UIImage imageNamed:@"D99GN4P63Q4F.png"]];
    
    _username.text = [NSString stringWithFormat:@"%@",[userInfo objectForKey:@"nickname"]];
    

}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)drawView{
    self.title = @"设置";
    _contentHeight = 0;
    
    self.view.backgroundColor = RGB(236, 240, 241);

//    NSArray *nameArr = [NSArray arrayWithObjects:@"头像",@"昵称",@"收货地址管理",@"修改密码",@"清理图片缓存",@"是否接收消息",nil];
        NSArray *nameArr = [NSArray arrayWithObjects:@"头像",@"昵称",@"收货地址管理",@"修改密码",nil];
    for (int i = 0; i<nameArr.count; i++) {
        UIView *itemView = [[UIView alloc]initWithFrame:CGRectMake(0, _contentHeight, kScreen_Width, 45)];
        itemView.backgroundColor = [UIColor whiteColor];
        if (i==0) {
            UILabel *lineLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, 0, kScreen_Width - 30, 0.5)];
            lineLabel.backgroundColor = [UIColor colorWithHexString:@"cecece"];
            [self.view addSubview:lineLabel];
            itemView.frame = CGRectMake(0, _contentHeight, kScreen_Width, 100);
        }
        [self.view addSubview:itemView];
        
        _contentHeight = _contentHeight + itemView.frame.size.height;
        
        //标题
        
        UILabel *nameLabel = [[UILabel alloc]initWithFrame:CGRectMake(15,10,kScreen_Width- 120,20)];
        if (i==0) {
            nameLabel.frame = CGRectMake(15,40,kScreen_Width- 120,20);
        }
        nameLabel.numberOfLines = 1;
        nameLabel.clipsToBounds = YES;
        nameLabel.textAlignment = NSTextAlignmentLeft;
        nameLabel.font = [UIFont systemFontOfSize:15];
        
        nameLabel.textColor = RGBJ(10);
        nameLabel.text = nameArr[i];
        [itemView addSubview:nameLabel];
        
        //加下划线
        if (i != nameArr.count - 1) {
        
            UILabel *lineLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, itemView.frame.size.height - 1, kScreen_Width - 30, 0.5)];
            lineLabel.backgroundColor = [UIColor colorWithHexString:@"cecece"];
            [itemView addSubview:lineLabel];
        }
        
        if (i==0) {
            UIView *rightView = [[UIView alloc]initWithFrame:CGRectMake(kScreen_Width - 85, 15, 70, 70)];
            rightView.backgroundColor = [UIColor colorWithHexString:@"cecece"];
            rightView.layer.masksToBounds = YES;
            rightView.layer.cornerRadius = 35;
            [itemView addSubview:rightView];
            
            UIImageView *rightImageView = [[UIImageView alloc]initWithFrame:CGRectMake(kScreen_Width - 83, 17, 66, 66)];
            self.imageView = rightImageView;
            rightImageView.layer.masksToBounds = YES;
            rightImageView.layer.cornerRadius = 33;
            rightImageView.image = [UIImage imageNamed:@"ad_0.png"];
            [itemView addSubview:rightImageView];
        }else if (i==1){
            UILabel *rightLabel = [[UILabel alloc]initWithFrame:CGRectMake(kScreen_Width- 215,10,200,20)];
            _username = rightLabel;
            rightLabel.numberOfLines = 1;
           rightLabel.clipsToBounds = YES;
            rightLabel.textAlignment = NSTextAlignmentRight;
            rightLabel.font = [UIFont systemFontOfSize:15];
            rightLabel.textColor = RGBJ(10);
            rightLabel.text = @"未设置";
            [itemView addSubview:rightLabel];
        }else if (i==4){
            UILabel *rightLabel = [[UILabel alloc]initWithFrame:CGRectMake(kScreen_Width- 115,10,100,20)];
            
            rightLabel.numberOfLines = 1;
            rightLabel.clipsToBounds = YES;
            rightLabel.textAlignment = NSTextAlignmentRight;
            rightLabel.font = [UIFont systemFontOfSize:15];
            rightLabel.textColor = RGBJ(10);
             rightLabel.text = @"20M";
            [itemView addSubview:rightLabel];
        }else if (i==5){
            
        }
        //添加点击按钮——覆盖在原来的View上
        UIButton *clickBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [clickBtn setTitle:@"" forState:UIControlStateNormal];
        [clickBtn setBackgroundColor:RGBA(255, 255, 255, 0)];
        clickBtn.tag = 100+i;
        [clickBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        clickBtn.frame = itemView.frame;//大小和位置
        [clickBtn addTarget:self action:@selector(handleAction:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:clickBtn];
    }
    
    _contentHeight = _contentHeight + 60;
    
    //添加点击按钮---添加一个按钮
    UIButton *clickBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [clickBtn setTitle:@"退出当前用户" forState:UIControlStateNormal];
    [clickBtn setFont:[UIFont systemFontOfSize:15]];
    [clickBtn setBackgroundColor:RGB(252, 103, 105)];
    clickBtn.layer.masksToBounds = YES;
    clickBtn.layer.cornerRadius = 2;
    [clickBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    clickBtn.frame = CGRectMake(15, _contentHeight, kScreen_Width - 30, 50);
    [clickBtn addTarget:self action:@selector(existCurrentUserInfo:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:clickBtn];
    
    UILabel *lineLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, kScreen_Width, 0.5)];
    lineLabel.backgroundColor = [UIColor grayColor];
    [self.view addSubview:lineLabel];
    
}

#pragma mark - 每一行动作的处理
-(void)handleAction:(UIButton *)btn{
    NSInteger tag = btn.tag - 100;
    if (tag == 0) {
        [self updateUserImage];
    }else if(tag == 1){
        [self changeNickname];
    }else if (tag == 2){
        [self manageAddressAction];
    }else if (tag == 3){
        [self changePwd];
    }
}

#pragma mark - 修改昵称
-(void)changeNickname{
    HNChangeNicknameController *changeNicknameVC = [[HNChangeNicknameController alloc]init];
    [self.navigationController pushViewController:changeNicknameVC animated:YES];
}

#pragma mark - 收货地址管理
-(void)manageAddressAction{
    AddressListController *addressVC = [[AddressListController alloc]init];
    [self.navigationController pushViewController:addressVC animated:YES];
}

#pragma mark - 修改密码
-(void)changePwd{
    HNChangePwdController *changePwdVC = [[HNChangePwdController alloc]init];
    [self.navigationController pushViewController:changePwdVC animated:YES];
}


#pragma mark - 退出当前用户
-(void)existCurrentUserInfo:(UIButton *)btn{
    
    
    [AppConfig removeUserInfo];

    [[EMClient sharedClient] logout:YES];
    [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@NO];
    

}


#pragma mark - 初始化用户信息
-(void)getUserInfo{
    
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:@"1",@"cur",@"1",@"isDoctor",nil];
    NSLog(@"param = %@",param);
    
    
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager manager] initWithBaseURL:[NSURL URLWithString:url_Base]];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:url_doctor_list parameters:param progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSError * error;
        NSLog(@"responseObject = %@",responseObject);
        
        NSLog(@"NSDictionary = %@",(NSDictionary *)responseObject);
        
        NSLog(@"NSArray = %@",(NSArray *)responseObject);
        
        NSLog(@"NSString = %@",(NSString *)responseObject);
        
        NSLog(@"Data = %@",(NSData *)responseObject);
        
        NSDictionary * data=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:&error];
        [self hideHud];
        if (error) {
            NSLog(@"====error1:%@",error);
            [self showHint:@"获取医生详情失败"];
            NSLog(@"==dict:%@",data);
            return;
        }
        NSLog(@"==dict:%@",data);
        
        NSString * result = [NSString stringWithFormat:@"%@",[data objectForKey:@"result"]];
        if ([result isEqualToString:@"1"]) {
            NSArray * obj = [NSArray arrayWithArray:[data objectForKey:@"obj"]];
            NSLog(@"------obj = %@",obj);
            
                        
            
            
        }else{
            NSString * info = [NSString stringWithFormat:@"%@",[data objectForKey:@"msg"]];
            if ([info isEqualToString:msg_InvalidLoginInformation]) {
                
                [AppConfig removeUserInfo];
                
                [[EMClient sharedClient] logout:YES];
                [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@NO];
                
                LoginViewController *loginVC = [[LoginViewController alloc]init];
                
                [self.navigationController pushViewController:loginVC animated:YES];
            }
            [self showHint:info];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull  error) {
        NSLog(@"====error:%@",error);
        [self hideHud];
        [self showHint:@"获取医生详情失败"];
    }];
    
    
}

#pragma mark -  上传头像
-(void)updateUserImage{
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        
        dispatch_async(dispatch_get_main_queue(),^{
            UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"更换头像" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"从相册选择", @"拍照", nil];
            actionSheet.delegate = self;
            actionSheet.tag = 1001;
            [actionSheet showInView:self.view];
            self.imagePicker = [[UIImagePickerController alloc]init];
            self.imagePicker.delegate = self;
            self.imagePicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
            self.imagePicker.allowsEditing = YES;
        });
    });
}

#pragma mark - 判断设备是否有摄像头
- (BOOL) isCameraAvailable
{
    return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
}
#pragma mark - UIActionSheet delegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (actionSheet.tag==1001) {
        _imagePicker = [[UIImagePickerController alloc] init];
        _imagePicker.editing = YES;
        _imagePicker.allowsEditing = YES;
        _imagePicker.delegate = self;
        if (buttonIndex == 0)
        {
            //相册
            _imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            //[self presentModalViewController:_imagePicker animated:YES];
            [self presentViewController:_imagePicker animated:YES completion:nil];
            
        }else if (buttonIndex == 1){
            //照相机
            if ([self isCameraAvailable]) {
                _imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
                //[self presentModalViewController:_imagePicker animated:YES];
                [self presentViewController:_imagePicker animated:YES completion:nil];
            }else{
                [self showHint:@"该设备没有摄像头"];
            }
        }else
        {
            //取消
        }
    }
    
}
#pragma mark - UIImagePicker delegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    //[picker dismissModalViewControllerAnimated:YES];
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    //UIImage *image = [[info objectForKey:UIImagePickerControllerEditedImage] retain];
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    [self performSelector:@selector(saveImage:) withObject:image afterDelay:0.5];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    //    [[UIApplication sharedApplication]setStatusBarStyle:UIStatusBarStyleLightContent];
    //[picker dismissModalViewControllerAnimated:YES];
    //保持状态栏颜色---为黑色
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
    [picker dismissViewControllerAnimated:YES completion:nil];
}

//上传图片
-(void)saveImage:(UIImage *)image{
    NSLog(@"image = %@",image);
    
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager manager] initWithBaseURL:[NSURL URLWithString:url_Base]];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [manager POST:url_update_userInfo_image parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        //压缩图片
        __block UIImage * changeImage = [self compressImage:image toTargetWidth:333];
        
        NSData *data = UIImagePNGRepresentation(changeImage);
        
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        // 设置时间格式
        formatter.dateFormat = @"yyyyMMddHHmmss";
        NSString *str = [formatter stringFromDate:[NSDate date]];
        NSString *fileName = [NSString stringWithFormat:@"%@.png", str];
        [formData appendPartWithFileData:data name:@"file" fileName:fileName mimeType:@"image/png"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        //打印下上传进度
        NSLog(@"上传进度");
        NSLog(@"%@",uploadProgress);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //上传成功
        NSLog(@"上传成功");
        NSError *error;
        NSDictionary * data = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:&error];
        
        NSLog(@"%@",data);
        
        
        [self hideHud];
        if (error) {
            NSLog(@"====error1:%@",error);
            return;
        }
        NSString * result = [NSString stringWithFormat:@"%@",[data objectForKey:@"result"]];
        
        
        if ([result isEqualToString:@"1"]) {
            _imageStr = [NSString stringWithFormat:@"%@",[data objectForKey:@"obj"]];
            NSLog(@"------obj = %@",_imageStr);
            
            NSString *imageStr = [NSString stringWithFormat:@"%@%@",url_Base,_imageStr];
            [_imageView sd_setImageWithURL:[NSURL URLWithString:imageStr] placeholderImage:nil];
            
            [self updateUserInfo];
            
        }else{
            NSString * info = [NSString stringWithFormat:@"%@",[data objectForKey:@"msg"]];
            if ([info isEqualToString:msg_InvalidLoginInformation]) {
                
                [AppConfig removeUserInfo];
                
                [[EMClient sharedClient] logout:YES];
                [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@NO];
                
                LoginViewController *loginVC = [[LoginViewController alloc]init];
                
                [self.navigationController pushViewController:loginVC animated:YES];
            }

            [self showHint:info];
        }
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //上传失败
        NSLog(@"上传失败");
        NSLog(@"%@",error.description);
    }];
    
}

//压缩图片
- (UIImage *)compressImage:(UIImage *)sourceImage toTargetWidth:(CGFloat)targetWidth {
    CGSize imageSize = sourceImage.size;
    
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    
    NSLog(@"width = %f,height = %f",width,height);
    
    CGFloat targetHeight = (targetWidth / width) * height;
    NSLog(@"targetWidth = %f targetHeight = %f",targetWidth,targetHeight);
    
    UIGraphicsBeginImageContext(CGSizeMake(targetWidth, targetHeight));
    [sourceImage drawInRect:CGRectMake(0, 0, targetWidth, targetHeight)];
    
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return newImage;
}

#pragma mark - updateUserInfo 更新用户信息
-(void)updateUserInfo{
    NSMutableDictionary *param = [NSMutableDictionary dictionaryWithObjectsAndKeys:static_sessionId,@"sessionId",nil];
    
    [param setObject:_imageStr forKey:@"photo"];
    
    NSLog(@"param = %@",param);
    
    
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager manager] initWithBaseURL:[NSURL URLWithString:url_Base]];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:url_update_userInfo parameters:param progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSError * error;
        NSLog(@"responseObject = %@",responseObject);
        
        NSDictionary * data=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:&error];
        [self hideHud];
        if (error) {
            NSLog(@"====error1:%@",error);
            [self showHint:@"更新用户信息失败"];
            NSLog(@"==dict:%@",data);
            return;
        }
        NSLog(@"==dict:%@",data);
        
        NSString * result = [NSString stringWithFormat:@"%@",[data objectForKey:@"result"]];
        if ([result isEqualToString:@"1"]) {
            _userInfo = [NSDictionary dictionaryWithDictionary:[data objectForKey:@"obj"]];
            NSLog(@"------obj = %@",_userInfo);
            
            NSString *userImageStr = [NSString stringWithFormat:@"%@",[_userInfo objectForKey:@"photo"]];
            if ([AppConfig isNULL:userImageStr]) {
                userImageStr = @"null";
            }
            NSString *userNickname = [NSString stringWithFormat:@"%@",[_userInfo objectForKey:@"nickname"]];
            if ([AppConfig isNULL:userNickname]) {
                
                userNickname = @"未设置";
            }
            NSString *userUserName = [NSString stringWithFormat:@"%@",[_userInfo objectForKey:@"mobile"]];
            if ([AppConfig isNULL:userUserName]) {
                userImageStr = @"未设置";
            }
            
            NSDictionary *saveDic = [NSDictionary dictionaryWithObjectsAndKeys:userImageStr,@"photo",userUserName,@"hnLoginName",userNickname,@"nickname", nil];
            
            
               [AppConfig saveUserInfo:saveDic];
         
        }else{
            NSString * info = [NSString stringWithFormat:@"%@",[data objectForKey:@"msg"]];
            if ([info isEqualToString:msg_InvalidLoginInformation]) {
                
                [AppConfig removeUserInfo];
                
                [[EMClient sharedClient] logout:YES];
                [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@NO];
                
                LoginViewController *loginVC = [[LoginViewController alloc]init];
                
                [self.navigationController pushViewController:loginVC animated:YES];
            }
            [self showHint:info];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull  error) {
        NSLog(@"====error:%@",error);
        [self hideHud];
        [self showHint:@"更新用户信息失败"];
    }];

}



@end
